<?php
	/** SNS類
	*	Date: 	2012-5-17
	*	Author:	merlin
	*/
	class SNS{	//class start
		
		private $_sdk;
		private $_api;
		
		public function __construct(array $params) {
			
			/** 
			* 必須設置appId與secret
			*/
			if(!isset($params['appId']) || empty($params['secret']) || !isset($params['secret']) || empty($params['secret'])) {
				throw new Exception("appId or secret is undefined!");
			}

			$type = (isset($params['type']) && !empty($params['type'])) ? $params['type'] : 'fb';
			switch ($type) {
				/** 
				* 新浪微博，必須設置redirect_uri(授权后的回调地址)
				*/
				case 'weibo':

					if(!isset($params['redirect_uri']) || empty($params['redirect_uri'])) {
						throw new Exception("redirect_uri is undefined!");
					}
					require_once("Vendor/Weibo/sdk/saetv2.ex.class.php");
					$sess_obj = new Session();
					if (isset($_REQUEST['code'])) {
						$saeTOAuthV2 = new SaeTOAuthV2($params['appId'], $params['secret']);
						$weibo_keys = array();
						$weibo_keys['code'] = $_REQUEST['code'];
						$weibo_keys['redirect_uri'] = $params['redirect_uri'];
						try {
							$weibo_token = $saeTOAuthV2->getAccessToken(
								(isset($params['response_type']) && in_array($params['response_type'], array('code', 'token'))) ? $params['response_type'] : 'code',
								$weibo_keys
							);
						} catch (OAuthException $e) {}
						if ($weibo_token) {
							$sess_obj->set('SNS_WEIBO_TOKEN', $weibo_token);
							setcookie('weibojs_' . $saeTOAuthV2->client_id, http_build_query($weibo_token));
						}
					}
					$weibo_token = $sess_obj->get('SNS_WEIBO_TOKEN');
					$this->_sdk = new SaeTClientV2($params['appId'] , $params['secret'], $weibo_token['access_token']);
					$this->_api = getLibClass('SNS_WEIBO', array('sdk' => $this->_sdk, 'redirect_uri' => $params['redirect_uri']));

					break;
				
				/** 
				* twitter,必須設置redirect_uri(授权后的回调地址)
				*/
				case 'twitter':

					if(!isset($params['redirect_uri']) || empty($params['redirect_uri'])) {
						throw new Exception("redirect_uri is undefined!");
					}

					require_once 'Vendor/Twitter/sdk/tmhOAuth.php';
					require_once 'Vendor/Twitter/sdk/tmhUtilities.php';
					$sess_obj = new Session();
					$this->_sdk = new tmhOAuth(array(
						'consumer_key'    => $params['appId'],
						'consumer_secret' => $params['secret'],
					));
					
					if (isset($_REQUEST['oauth_verifier'])) {

						$oauth_token = $sess_obj->get('SNS_TRITTER_OAUTH_TOKEN');
						$oauth_token_secret = $sess_obj->get('SNS_TRITTER_OAUTH_TOKEN_SECRET');
						if(!empty($oauth_token) && $oauth_token == $_REQUEST['oauth_token'] && !empty($oauth_token_secret)) {
							$this->_sdk->config['user_token']  = $oauth_token;
							$this->_sdk->config['user_secret'] = $oauth_token_secret;
							$code = $this->_sdk->request('GET', $this->_sdk->url('oauth/access_token', ''), array(
								'oauth_verifier' => $_REQUEST['oauth_verifier']
							));
							if ($code == 200) {
								$sess_obj->set('SNS_TRITTER_OAUTH_TOKEN', null);
								$sess_obj->set('SNS_TRITTER_OAUTH_TOKEN_SECRET', null);
								$access_token = $this->_sdk->extract_params($this->_sdk->response['response']);
								if (isset($access_token['oauth_token']) && !empty($access_token['oauth_token']) && isset($access_token['oauth_token_secret']) && !empty($access_token['oauth_token_secret'])) {
									$sess_obj->set('SNS_TRITTER_ACCESS_TOKEN', $access_token);
									$this->_sdk->config['user_token']  = $access_token['oauth_token'];
									$this->_sdk->config['user_secret'] = $access_token['oauth_token_secret'];
								}
							}
						}

					} else {

						$access_token = $sess_obj->get('SNS_TRITTER_ACCESS_TOKEN');
						if (isset($access_token['oauth_token']) && !empty($access_token['oauth_token']) && isset($access_token['oauth_token_secret']) && !empty($access_token['oauth_token_secret'])) {
							$this->_sdk->config['user_token']  = $access_token['oauth_token'];
							$this->_sdk->config['user_secret'] = $access_token['oauth_token_secret'];
						}

					}

					$this->_api = getLibClass('SNS_TWITTER', array('sdk' => $this->_sdk, 'redirect_uri' => $params['redirect_uri'], 'sess_obj' => $sess_obj));

					break;
				
				/** 
				* QQ,必須設置redirect_uri(授权后的回调地址)
				*/
				case 'qq':
					if (!isset($params['redirect_uri']) || empty($params['redirect_uri'])) {
						throw new Exception("redirect_uri is undefined!");
					}
					require_once("Vendor/QQWeibo/sdk/Tencent.php");
					OAuth::init($params['appId'] , $params['secret']);
					Tencent::$debug = false;
					if (isset($_GET['code'])) {
						$code = $_GET['code'];
						$openid = $_GET['openid'];
						$openkey = $_GET['openkey'];
						$url = OAuth::getAccessToken($code, $params['redirect_uri']);
						$r = Http::request($url);
						parse_str($r, $out);
						if ($out['access_token']) {
							$_SESSION['t_access_token'] = $out['access_token'];
							$_SESSION['t_expire_in'] = $out['expire_in'];
							$_SESSION['t_code'] = $code;
							$_SESSION['t_openid'] = $openid;
							$_SESSION['t_openkey'] = $openkey;
						}
					}
					$this->_sdk = 'Tencent';
					$this->_api = getLibClass('SNS_QQWeibo', array('sdk' => $this->_sdk, 'redirect_uri' => $params['redirect_uri']));

					break;
				
				/** 
				* facebook，默認
				*/
				case 'fb':
				default:

					require_once("Vendor/Facebook/sdk/facebook.php");
					$config = array(
						'appId'    => $params['appId'],
						'secret'   => $params['secret']
					);
					isset($params['fileUpload']) && $config['fileUpload'] = $params['fileUpload'];
					isset($params['state']) && $config['state'] = $params['state'];
					$this->_sdk = new Facebook($config);
					$this->_api = getLibClass('SNS_FB', $this->_sdk);

					break;
			}

		}
		
		/** 統一調用api方法
		* @method	String	方法名
		* [, param1] [, param2 ] [, param3 ]......
		* example
		 *  - $sns->api('getUserInfo') = getUserInfo()
		 *  - $sns->api('getLoginUrl', array('redirect_uri' => $redirect_uri, 'scope' =>$scope)) = getLoginUrl(array('redirect_uri' => $redirect_uri, 'scope' =>$scope)))
		*/
		public function api() {
			$args = func_get_args();
			$method = array_shift($args);
			if (is_callable(array($this->_api, $method))) {
				return call_user_func_array(array($this->_api, $method), $args);
			} elseif (is_callable(array($this->_sdk, $method))) {
				return call_user_func_array(array($this->_sdk, $method), $args);
			}
		}
	

	}	// class end
?>
